
package com.whosly.mysql.protocol.packet.impl;

import com.whosly.mysql.protocol.packet.jdbc.MySQLPacket;
import com.whosly.mysql.protocol.packet.util.NettyBufferUtil;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

/**
 * MySql包 外层结构
 *
 * @author fengyang(yueny09@163.com)
 * @date 2023年06月25日 下午1:26
 */
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BinaryPacket
        extends MySQLPacket
{
    public static final byte OK = 1;
    public static final byte ERROR = 2;
    public static final byte HEADER = 3;
    public static final byte FIELD = 4;
    public static final byte FIELD_EOF = 5;
    public static final byte ROW = 6;
    public static final byte PACKET_EOF = 7;

    @Getter
    private byte[] data;

    @Override
    public int calcPacketSize() {
        return data == null ? 0 : data.length;
    }

    @Override
    public ByteBuf writeBuf(ByteBuf buffer)
    {
        NettyBufferUtil.writeUB3(buffer, calcPacketSize());
        buffer.writeByte(getPackId());

        buffer.writeBytes(data);

        return buffer;
    }

    @Override
    public void read(byte[] bodyBytes)
    {
        this.data = bodyBytes;
    }

    @Override
    public String getPacketInfo() {
        return "MySQL Binary Packet";
    }

}
